<template>

	<div v-waterMarker style="display: flex;height:100%;    flex-direction: column;" v-loading="loadingState" element-loading-background="transparent">

		<div class="top-card merak-card" style="height:80px;">
			
			<div class="uidname">
				「 {{routerName}} 」的权限
			</div>
			<div class="copy_user_title">
						<!-- <el-button style="align-self: flex-start" @click="back">返回</el-button> -->
						<div class="copy_userinfo" style="margin-right:20px;">
							复制
							<div class="user_val">
								<!-- <el-button type="primary" link  @click="godetail(row)">
					请选择 </el-button> -->
								<el-tree-select class="qf_tree_select" v-model="userId" :data="userTreeData"
									:render-after-expand="false" filterable :filter-node-method="filterNodeMethod"
									:disable-branch-nodes="true" default-expand-all @node-click="getTreeUser"
									style="width: 200px;margin: 0 10px;" />
							</div>
							的权限
						</div>

						
							<!-- <el-button type="primary" @click="authSave()">{{ $t("merak.save") }}</el-button> -->
						

					</div>

		</div>


		<el-scrollbar :style="{ height:  `calc(100% - 80px)`  }">

			<div class="merak-container-has-aside" curPageName="324srerssfs2w3r">
				<!-- 包装层 可在末尾追加弹窗、抽屉等组件 curPageName 用于页面检索 -->
				<div class="merak-aside">
					<div class="qx_menu">
						<el-input placeholder="搜索" v-model="filterText" style="margin-bottom: 10px;">
					</el-input>
					
						<div class="personall">
						<div>
							<el-tree empty-text="sdsd" :current-node-key="defaultnodeid"  :default-checked-keys="checked_id_list"  @node-click="treelabelClick" :data="pageAuth" show-checkbox
								@check="treechange_person" default-expand-all node-key="id" ref="personallTreeRef"
								highlight-current :filter-node-method="filterNode" :props="defaultProps" >
							</el-tree>
						</div>

						<!-- 
								<div v-if="searchactive == false">
									<el-checkbox-group v-model="searchchecked" class="searchPersonAll">
										<el-checkbox v-for="item in searchPersonData"
											:label="item.id">{{ item.label }}</el-checkbox>
									</el-checkbox-group>
								</div> -->




					</div>
				




					
					</div>
					
				</div>
				<div class="merak-card merak-container-has-search">
					<!-- 主容器 可随意放置高级搜索等组件 也可不放置 -->
					<div class="merak-table-wrapper">
						
						<div class="merak-overflow-y" >

							<div class="empty_box" v-if="authRightArr.length==0">
								<img src="/src/assets/images/empty.png"/>
							</div>

							<div v-else>
								<div class="auth_ever" v-for="(authParent, index) in authRightArr">
									<!-- 一级 -->
									
									<div class="auth_one">
										{{ authParent.title }} 
										<el-switch @change="changeTwo('lev1', authParent)" :disabled="!rightdisabled" size="small" v-model="authParent.is_checked" />
									</div>

									<div class="auth_two">
										<div class="auth_two_l">
											当前页面
										</div>
										<div class="auth_two_R">
											<div class="auth_four">
												<el-checkbox :dataId="authParent.id"  @change="changeTwo('lev1', authParent)"
															v-model="authParent.is_checked"  :disabled="!authParent.is_checked"
															name="type">
															<span style="color:#000">查看 </span>
														</el-checkbox>
											</div>

											<div class="auth_four" v-for="(authFour, index) in authParent.curpageAuth">
												<el-checkbox :dataId="authFour.id"  @change="changeTwo('lev3', '')"
													v-model="authFour.is_checked" :value="authFour.title" :disabled="!authParent.is_checked"
													name="type"> 
													<span style="color:#000">{{ authFour.title }}</span>
												</el-checkbox>
											</div>
										</div>

									</div>


									<div class="auth_two" v-for="(sonpage, index) in authParent.sonpageAuth">
										<div class="auth_two_l">
											{{sonpage.title}} <el-switch :disabled="!authParent.is_checked" @change="changeTwo('lev2', sonpage)" size="small" v-model="sonpage.is_checked" />
										</div>
										<div class="auth_two_R">
											<div class="auth_four">
												<el-checkbox :dataId="sonpage.id"  @change="changeTwo('lev2', sonpage)"
															v-model="sonpage.is_checked"  :disabled="!sonpage.is_checked"
															name="type">
															<span style="color:#000">查看</span>
												</el-checkbox>
											</div>

											<div class="auth_four" v-for="(authFour, index) in sonpage.children">
												<el-checkbox :dataId="authFour.id"  @change="changeTwo('lev3', '')"
													v-model="authFour.is_checked" :value="authFour.title" :disabled="!sonpage.is_checked"
													name="type">
													<span style="color:#000">{{ authFour.title }}</span>
												</el-checkbox>
											</div>


										</div>

									</div>







									


							
									<!-- <div class="auth_two" 
										v-for="(authTwo, index) in authParent.children">
						
										<div class="auth_two_l">
											{{ authTwo.title }} 
											
											
											
											<el-switch size="small" @change="changeTwo('lev2', authTwo)"
												v-model="authTwo.is_checked" />
										</div>
										<div class="auth_two_R">
											<div class="auth_three" v-for="(authThree, index) in authTwo.children">
												<div class="auth_three_l">
													{{ authThree.title }} <el-switch size="small"
														@change="changeTwo('lev3', authThree)"
														:disabled="!authTwo.is_checked" v-model="authThree.is_checked" />
												</div>

												<div class="auth_three_R" v-if="authThree.children">
													<div class="auth_four" v-for="(authFour, index) in authThree.children">

														<el-checkbox :dataId="authFour.id" :disabled="!authThree.is_checked"
															v-model="authFour.is_checked" :value="authFour.title"
															name="type">
															<span style="color:#000">{{ authFour.title }}</span>
														</el-checkbox>

													</div>

			

												</div>


											</div>






										</div>

									</div> -->

								</div>
							</div>


							
						</div>

						

					</div>
				</div>
			</div>
	    </el-scrollbar>

	</div>





		
















</template>

<script setup lang="ts" name="caseOne">

import { ref, reactive, onMounted, getCurrentInstance,watch } from "vue";
import { Plus, Edit, Delete, EditPen, CopyDocument } from '@element-plus/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import searchBar from "@/components/SearchBar";
import { userAuthListApi, saveUserAuthApi, getUserListTreeApi,listMenuApi,getRightApi,saveCopyAuthApi } from "@/api/modules/permission";
import { moreConfirm, confirmWarningMsg, successMsg, warnMsg, failMsg, confirmSuccessMsg, delConfimMsg } from "@/utils/messageUtils";
import { useTabsStore } from "@/stores/modules/tabs";


const tabsStore = useTabsStore();

const router = useRouter();
const route = useRoute();

//console.log(router.currentRoute.value.query.id)

const loadingState = ref(false);//页面loading状态

const defaultnodeid=ref(1);




// 选人弹框
const filterText=ref('');
const personallTreeRef=ref()
	
	


	

let persondata=reactive([]);

watch(filterText, (val) => {
	personallTreeRef.value!.filter(val)
})



const rightdisabled=ref(true);


// 左侧选择权限菜单，获取右侧权限数据
const treelabelClick = (data, node, obj) => {
	console.log(data,node)
	//节点2级以后发送请求
	if(node.level>1){
		rightdisabled.value=node.checked;
		defaultnodeid.value=data.id;
		getRightDateFun(uid.value,data.id)
	}else{
		authRightArr.value=[]
	}


}
//选人搜索

const filterNode = (value, data) => {
	if (!value) return true;
	var value = value.toLowerCase();
	var label = data.title.toLowerCase();
	return label.indexOf(value) !== -1;
}
//左侧选人修改 勾选

const treechange_person = (data, node, obj) => {
console.log(data, node, obj)

console.log(defaultnodeid.value)
console.log(data.id)   
console.log(pageAuth.value)  
const new_pageAuth=pageAuth.value;


var curstatus=true;
for (let index = 0; index < new_pageAuth.length; index++) {
	const onemenu=new_pageAuth[index];
	if(onemenu.id==data.id){
		onemenu.is_checked=!onemenu.is_checked;
		curstatus=onemenu.is_checked;
	}else{
		if(onemenu.children){
			for (let index = 0; index < onemenu.children.length; index++) {
				var twomenu= onemenu.children[index];
				if(twomenu.id==data.id){
					twomenu.is_checked=!twomenu.is_checked;
		            curstatus=twomenu.is_checked;

				}

			}

		}

	}

}








console.log('------'+curstatus)
if(data.id==defaultnodeid.value){
	
	
	rightdisabled.value=data.is_checked;
	if(data.is_checked==false){
		console.log("勾选掉，右侧清楚")

console.log(authRightArr.value)
const quxiaoarr=authRightArr.value;

for (let index = 0; index < authRightArr.value.length; index++) {
const _obj=authRightArr.value[index];
_obj.is_checked=false;
const curpageAuth=_obj.curpageAuth;
for (let index = 0; index < curpageAuth.length; index++) {
	curpageAuth[index].is_checked = false;

}
const sonpageAuth=_obj.sonpageAuth;
for (let index = 0; index < sonpageAuth.length; index++) {
	sonpageAuth[index].is_checked = false;
	const lastobj=sonpageAuth[index].children;
	if(lastobj){
		for (let index = 0; index < lastobj.length; index++) {
			lastobj[index].is_checked = false;
		}

	}



}
}


}
}







authSave(data.id,'left')
//    personrightArr.value = personallTreeRef.value.getCheckedNodes(true, false);


// 	searchchecked.value = personallTreeRef.value.getCheckedKeys(true, false);

}

















//#region 复制员工信息至当前页面

let userId = ref("");//复制某人的用户ID
const userTreeData = ref([]),
	treeData = ref([]);
let keyMap = reactive({ id: 'value' })
const defaultProps = {
	children: 'children',
	label: 'title',
	disabled: 'disabled',
}
const getUserTree = () => {
	getUserListTreeApi().then(res => {
		//console.log(res)
		if (res.code == ResultEnum.SUCCESS) {
			let data = res.data.UserTreeList;
			let newArr = resetKey(data, keyMap);
			treeData.value = newArr;
			userTreeData.value = newArr;
		} else {
			failMsg(res.message);
		}
	})
}

const resetKey = (data, keyMap) => {
	let allObj = data.map(d => {
		let objs = Object.keys(d).reduce((newData, key) => {
			let newKey = keyMap[key] || key
			newData[newKey] = d[key]
			return newData
		}, {})
		if (d.children && d.children.length) {
			objs.children = resetKey(d.children, keyMap)
		}
		return objs;
	})
	return allObj;
}
//过滤员工
const filterNodeMethod = (value, data) => data.label.includes(value);
getUserTree();//初始化获取员工列表
const chooseCopyId = ref("");

//点击选择员工
const getTreeUser = (e) => {
	if (e.isUser) {
		userId.value = e.label;
		// uid.value=e.value;
		chooseCopyId.value = e.value.split("-")[1];
		listAuth(chooseCopyId.value,'copy')
		if (routerType == 'batch') {
		post_uid_list.value = post_uid_list.value;
	} else {
		post_uid_list.value = [uid.value]
	}
		
		saveCopyAuthApi({"uid_batch":post_uid_list.value,"uid_origin":chooseCopyId.value}).then(res => {
				if (res.code == ResultEnum.SUCCESS) {
	
	
					successMsg(res.message);
	
					
				}else{
					failMsg(res.message);
				}
})
	}
}



//#endregion

const routerType = router.currentRoute.value.query.type;
const routerName = router.currentRoute.value.query.name;





const uid = ref("");
const post_uid_list = ref([]);

if (routerType == 'batch') {
	post_uid_list.value = router.currentRoute.value.query.id;
	post_uid_list.value = JSON.parse(post_uid_list.value)
} else {
	uid.value = router.currentRoute.value.query.id;
}





const pageAuth = ref([]);

const authRightArr = ref([]);
const checked_id_list=ref([]);
//初始化获取权限接口
const listAuth = (id,type) => {
	loadingState.value = true;
	listMenuApi({ uid: id }).then(res => {
		loadingState.value = false;

		if (res.code == ResultEnum.SUCCESS) {

			const postdata = res.data.list;

			const checkedList=res.data.checked_id_list;
			if(postdata.length>0){
				postdata[0]["disabled"]=true;
			}
            for (let index = 0; index < postdata.length; index++) {
				const one_obj = postdata[index];
				const two_arr = one_obj.children;
				var del_id='';
				if(two_arr){
					for (let index = 0; index < two_arr.length; index++) {
						const two_obj = two_arr[index];
						if(two_obj.is_checked==false){
							del_id=two_obj.parent_id+'';
							

							

						}
		
					}

				
							let delindex = checkedList.indexOf(del_id);
							
							if (delindex !== -1) {
							
								checkedList.splice(delindex, 1);
							}




				}


			}
			


			//myArray = myArray.filter(item => item !== "banana");

			// for (let index = 0; index < postdata.length; index++) {
			// 	const one_obj = postdata[index];
			// 	const two_arr = one_obj.children;
			// 	if (two_arr) {
			// 		for (let index = 0; index < two_arr.length; index++) {
			// 			const two_obj = two_arr[index];
			// 			const three_arr = two_obj.children;
			// 			if (three_arr) {
			// 				for (let index = 0; index < three_arr.length; index++) {
			// 					const three_obj = three_arr[index];
			// 					const four_arr = three_obj.children;
			// 					if (four_arr) {

			// 						for (let index = 0; index < four_arr.length; index++) {
			// 							const four_obj = four_arr[index];
			// 							const five_arr = four_obj.children;
			// 							//console.log("ssssssssssssssss")
			// 							//console.log(four_obj)
			// 							if (five_arr) {
			// 								for (let index = 0; index < five_arr.length; index++) {
			// 									four_arr.push(five_arr[index])
			// 								}
			// 							}
			// 						}

			// 					}


			// 				}
			// 			}

			// 		}

			// 	}



			// }






			//console.log(postdata)




			Object.assign(pageAuth.value, postdata)
			console.log(checkedList)

			checked_id_list.value=checkedList;


			if(type=="copy"){
				authRightArr.value=[];
				uid.value=id;
			}

	

			
			//getRightDateFun(id,defaultnodeid.value)


		} else {
			failMsg(res.message);
		}
	}, err => {
		//console.log(err)
	})
}





listAuth(uid.value)



const getRightDateFun = (id,auth_id) => {
	loadingState.value = true;
	getRightApi({ uid: id,auth_id:auth_id }).then(res => {
		//console.log(res)
		loadingState.value = false;
		if (res.code == ResultEnum.SUCCESS) {
			const res_auth_list=res.data.auth_list;
			console.log(res_auth_list)



			
			for (let index = 0; index < res_auth_list.length; index++) {
				const _obj = res_auth_list[index];
				var curpage_children=[];
				var sonpage_children=[];
				const two_objs_arr = _obj.children;
			    if (two_objs_arr) {
					for (let index = 0; index < two_objs_arr.length; index++) {
						var  two_obj=two_objs_arr[index];
							if(two_obj.children){
								sonpage_children.push(two_obj)

							}else{
								curpage_children.push(two_obj)
								
							}



					}

				}

				_obj["curpageAuth"]=curpage_children;
				_obj["sonpageAuth"]=sonpage_children;
				


				

			}


			console.log(res_auth_list)


			authRightArr.value=res_auth_list;







		} else {
			failMsg(res.message);
		}
	})
}



//保存权限
const authSave = (id,type) => {


	const menu_check=personallTreeRef.value!.getCheckedKeys(false);
	const half_check=personallTreeRef.value!.getHalfCheckedKeys();
	console.log(half_check)
	
	// const onearr = auth_id_list.concat(menu_check);
	


	const menu_check_all = half_check.concat(menu_check);
	console.log(auth_id_list)



	
	const oldchenckall = JSON.parse(JSON.stringify(checked_id_list.value))
	const oldchenckall_new=[]
	for (let index = 0; index < oldchenckall.length; index++) {
		oldchenckall_new.push(Number(oldchenckall[index]))

	}
	console.log(menu_check_all)
	console.log(oldchenckall_new)
	let set1 = new Set(menu_check_all);  
    let set2 = new Set(oldchenckall_new);  
    let difference2 = [...set1].filter(x => set2.size === 0 || !set2.has(x));  


	console.log(difference2)





	


	var auth_id_list = [];
	const postdata = JSON.parse(JSON.stringify(authRightArr.value))
	for (let index = 0; index < postdata.length; index++) {
		const one_obj = postdata[index];
		if (one_obj.is_checked) {

			auth_id_list.push(one_obj.id);
			const two_arr = one_obj.curpageAuth;
			
			if (two_arr) {
				for (let index = 0; index < two_arr.length; index++) {
					const two_obj = two_arr[index];
					if (two_obj.is_checked) {
						auth_id_list.push(two_obj.id);
						
					}
				}

			}

			const two_arr_son = one_obj.sonpageAuth;
			for (let index = 0; index < two_arr_son.length; index++) {
				var two_son_obj=two_arr_son[index];
				if (two_son_obj.is_checked) {
					auth_id_list.push(two_son_obj.id);
					const three_arr = two_son_obj.children;
					if (three_arr) {
						for (let index = 0; index < three_arr.length; index++) {
							const fourobj= three_arr[index];
							if (fourobj.is_checked) {
								auth_id_list.push(fourobj.id);
							}

						}




					}
					
				}


			}




		}

	}

	



	//const auth_id_list_post = auth_id_list.concat(menu_check_all);
	

	if (routerType == 'batch') {
		post_uid_list.value = post_uid_list.value;
	} else {
		post_uid_list.value = [uid.value]
	}


	console.log(defaultnodeid.value)
	var postactiveid=defaultnodeid.value;

	if(type=='left'){
		postactiveid=id;
	}

	loadingState.value=true;
	saveUserAuthApi({active_id:postactiveid,auth_id_left_list:menu_check_all,auth_id_right_list:auth_id_list,uid_list: post_uid_list.value }).then(res => {
		if (res.code == ResultEnum.SUCCESS) {
			loadingState.value=false;
			//.successMsg('保存成功!');
			//back();
		} else {
			failMsg(res.message);
		}
	}, err => {
		//console.log(err)
	})
}


const changeTwo = (optionKey, data) => {
	//console.log(data)
	console.log(optionKey)
		if (data.is_checked == false) {
			if (optionKey == 'lev1') {
                const curpageAuth=data.curpageAuth;
				for (let index = 0; index < curpageAuth.length; index++) {
					curpageAuth[index].is_checked = false;

				}
				const sonpageAuth=data.sonpageAuth;
				for (let index = 0; index < sonpageAuth.length; index++) {
					sonpageAuth[index].is_checked = false;
					const lastobj=sonpageAuth[index].children;
					if(lastobj){
						for (let index = 0; index < lastobj.length; index++) {
							lastobj[index].is_checked = false;
						}

					}



				}

			}
			

			if (optionKey == 'lev2') {
               console.log(data)
			   for (let index = 0; index < data.children.length; index++) {
				    data.children[index].is_checked = false;
					
				}
			}





		}


	// if (data.is_checked == false) {

	// 	if (optionKey == 'lev2') {
	// 		let three_arr = data.children;
	// 		if (three_arr) {
	// 			for (let index = 0; index < three_arr.length; index++) {
	// 				const three_ever = three_arr[index];
	// 				three_ever.is_checked = false;

	// 				let four_arr = three_ever.children;
	// 				if (four_arr) {

	// 					for (let index = 0; index < four_arr.length; index++) {
	// 						const four_ever = four_arr[index];
	// 						four_ever.is_checked = false;
	// 					}



	// 				}




	// 			}
	// 		}
	// 	} else {

	// 		let four_arr = data.children;
	// 		if (four_arr) {
	// 			for (let index = 0; index < four_arr.length; index++) {
	// 				const four_ever = four_arr[index];
	// 				four_ever.is_checked = false;
	// 			}

	// 		}
	// 	}
	// }
	authSave()
}


const back = () => {
	tabsStore.removeTabs(route.fullPath);
	router.push({ path: "/staff/permissionAssignment" });
};
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>